<template>
  <div>
    <ValidationProvider name="所在街道" rules="required" v-slot="{ errors }">
      <van-field
        readonly
        clickable
        label="所在街道"
        :value="label"
        placeholder="请选择所在街道"
        @click="showTownPicker = true"
        :error-message="errors[0]"
      />
    </ValidationProvider>

    <!-- 街道picker -->
    <van-popup v-model="showTownPicker" position="bottom" get-container="body">
      <van-picker
        show-toolbar
        value-key="label"
        :columns="townColumns"
        @cancel="showTownPicker = false"
        @confirm="onConfirmTown"
      />
    </van-popup>
  </div>
</template>

<script>
import { ValidationProvider, extend } from "vee-validate";
import { required } from "vee-validate/dist/rules";
import zh from "vee-validate/dist/locale/zh_CN";
import { getArea } from "@/api/user.js";
extend("required", {
  ...required,
  message: zh.messages["required"]
});
import Bus from "@/views/userInfo/components/bus";
export default {
  data() {
    return {
      townVal: this.value,
      showTownPicker: false,
      townColumns: []
    };
  },
  props: {
    value: {}
  },
  computed: {
    label() {
      let item = this.townColumns.filter(m => m.value == this.townVal)[0];
      if (item) {
        return item.label;
      } else {
        return "";
      }
    }
  },
  created() {
    const _this = this;
    Bus.$on("areaChange", function(val) {
      if (val) {
        getArea({
          pid: val
        }).then(({ data }) => {
          _this.townColumns = data.map(m => ({
            label: m.name,
            value: m.id
          }));
        });
      }
    });
  },
  destroyed() {
    Bus.$off("areaChange");
  },
  methods: {
    onConfirmTown(obj) {
      this.$emit("input", obj.value);
      this.showTownPicker = false;
      this.townVal = obj.value;
    }
  },
  components: {
    ValidationProvider
  }
};
</script>

<style lang='scss'>
</style>
